﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;

using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.Waimai;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands.Waimai
{

    public sealed class ShoppingCardCleanNoStockCommandHandler : BaseCommandHandler, IRequestHandler<ShoppingCardCleanNoStockCommand, BaseResult<string>>
    {
        private readonly IMbrStoreRepository _mbrStoreRepository;
        public ShoppingCardCleanNoStockCommandHandler(IMbrStoreRepository mbrStoreRepository, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _mbrStoreRepository = mbrStoreRepository;
        }

        public async Task<BaseResult<string>> Handle(ShoppingCardCleanNoStockCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var storeinfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
            if (storeinfo == null)
            {
                return new BaseResult<string>("", 9999, "门店信息有误！");
            }
            var stockreq = new ProductStockQueryReq { shopid = storeinfo.RelationId, product = new List<ProductStockReq>() };
            var url = "TakeOut/v1/ShoppingCart/GetList";
            var data = new { request.Mobile, request.StoreId };
			var listskus = await GetDrinkSkus().ConfigureAwait(false);

			var result = await PostThirdApiAsync<List<TakeOutShoppingCartBaseRsp>>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);

            if (result.Code == 0 &&(result.Content!=null && result.Content.Count>0))
            {
                foreach (var item in result.Content)
                {
					
					stockreq.product.Add(new ProductStockReq
                    {
                        pid = $"{item.GoodsRelationId}",
                        count = item.GoodsQuantity
                    });
                }
            }
           
            List<int> GoodsBaseIds = new List<int>();

			 
			var stockResult = await NetICService.Productstockquery(stockreq).ConfigureAwait(false);
            if (stockResult != null && stockResult.product.Any())
            {
                foreach (var item in result.Content)
                {
					var a = listskus.Any(c => c.GoodsRelationId == item.GoodsRelationId);
					if (a) {
						if(item.Status == 0) {
							GoodsBaseIds.Add(item.GoodsBaseId);
						}
						continue;
					}
					var p = stockResult.product.SingleOrDefault(c => c.pid == $"{item.GoodsRelationId}");
                    if (p == null)
                    {
                        GoodsBaseIds.Add(item.GoodsBaseId);
                        //return new BaseResult<PaymentRsp>(null, 999, $"{item.GoodsBaseId} 不存在");
                    }
                    else
                    {
                        
                        if (p.count < item.GoodsQuantity || item.Status==0)
                        {
                            GoodsBaseIds.Add(item.GoodsBaseId);
                        }
                    }
                }
            }
            if (GoodsBaseIds.Count==0)
            {
                return new BaseResult<string>("", 0, "");
            }
            url = "TakeOut/v1/ShoppingCart/CleanByIds";
            var data1 = new { request.StoreId, request.Mobile, GoodsBaseIds };
            return await PostAsync<BaseResult<string>>(url, JsonConvert.SerializeObject(data1)).ConfigureAwait(false);
        }

    }
}
